package com.sangeng.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sangeng.domain.ResponseResult;
import com.sangeng.entity.Link;
import com.sangeng.service.ILinkService;
import com.sangeng.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/content/link")
public class LinkController {

    @Autowired
    private ILinkService linkService;

    @GetMapping("/list")
    public ResponseResult list(String name, String status, int pageNum, int pageSize) {
        LambdaQueryWrapper<Link> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(name), Link::getName, name);
        wrapper.eq(StringUtils.hasText(status), Link::getStatus, status);
        Page<Link> page = new Page<>(pageNum, pageSize);
        Page<Link> page1 = linkService.page(page, wrapper);

        List<Link> links = page1.getRecords();

        PageVo pageVo = new PageVo(links, page1.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    // 新增分类
    @PostMapping
    public ResponseResult add(@RequestBody Link link) {
        linkService.save(link);
        return ResponseResult.okResult();
    }

    // 详情
    @GetMapping("/{id}")
    public ResponseResult getInfo(@PathVariable("id") Long id) {
        Link link = linkService.getById(id);
        return ResponseResult.okResult(link);
    }

    // 更新分类
    @PutMapping
    public ResponseResult update(@RequestBody Link link) {
        linkService.updateById(link);
        return ResponseResult.okResult();
    }

    // 删除分类
    @DeleteMapping("/{id}")
    public ResponseResult delete(@PathVariable("id") Long id) {
        linkService.removeById(id);
        return ResponseResult.okResult();
    }

    // 改变状态
    @PutMapping("/changeLinkStatus")
    public ResponseResult changeLinkStatus(@RequestBody Link link) {
        Link linkRes = linkService.getById(link.getId());
        linkRes.setStatus(link.getStatus());
        linkService.updateById(linkRes);
        return ResponseResult.okResult();
    }
}
